/**
 * File  : Event.cc
 * Time  : 2014-12-17 14:44
 * Author: KashingLee
 * Ref   : mooon
 */
#include <sys/time.h>
#include "Event.h"

Event::Event() {
  int ret = pthread_cond_init(&event_, &attr_); 
  if (ret) {
    throw ThreadException(THREAD_EVENT_INIT);
  }
}
Event::~Event() {
  pthread_cond_destroy(&event_);
}

void Event::Wait(Mutex& mutex) {
  int ret = pthread_cond_wait(&event_, &mutex.mutex_);   
  if (ret) {
    throw ThreadException(THREAD_EVENT_WAIT);
  }
}

void Event::TimeWait(Mutex& mutex, uint32_t seconds) {
  if (!seconds) {
    Wait(mutex);
  } else {
    struct timeval now;
    struct timespec tsp;
    gettimeofday(&now, NULL);
    tsp.tv_sec  = now.tv_sec;
    tsp.tv_nsec = now.tv_usec *1000; 
    tsp.tv_sec += seconds;
    //TODO 
    int ret = pthread_cond_timedwait(&event_,\
        &mutex.mutex_, &tsp);
    if (ret) {
      throw ThreadException(THREAD_EVENT_TIMEDWAIT);
    }

  }
}

void Event::Signal() {
  int ret = pthread_cond_signal(&event_);
  if (ret) {
    throw ThreadException(THREAD_EVENT_SIGNAL);
  }
}
void Event::Broadcast() {
  int ret = pthread_cond_broadcast(&event_);
  if (ret) {
    throw ThreadException(THREAD_EVENT_BROADCAST);
  }
}
